using System;
using System.IO;
using JetBrains.Annotations;
using Kaleida.ServiceMonitor.Framework;
using Kaleida.ServiceMonitor.Model.Runtime;
using Kaleida.ServiceMonitor.Model.Parsing;

namespace Kaleida.ServiceMonitor.Model.ScriptDirectives
{
    public class IncludeDirective : IScriptDirective
    {
        private readonly string scriptPath;
        private readonly string scriptContent;

        public IncludeDirective([NotNull] string scriptPath)
        {
            this.scriptPath = scriptPath;
            if (scriptPath == null) throw new ArgumentNullException("scriptPath");
            if (scriptPath.Trim() == "") throw new ArgumentException("Cannot be blank", "scriptPath");
            if(!File.Exists(scriptPath)) throw new ArgumentException(string.Format("Script '{0}' does not exist", scriptPath), "scriptPath");

            scriptContent = File.ReadAllText(scriptPath);
        }

        public CompiledNode Apply([NotNull] CompiledScriptModule module)
        {
            if (module == null) throw new ArgumentNullException("module");

            var compiledScript = scriptContent.ParseAndBuild(module.Name);
            return compiledScript.Root;
        }
    }
}